package api.data.controller;

import api.data.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import api.data.pojo.SysPermission;
import api.data.utils.JSONResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@Api(tags = "社区接口")
@Slf4j
@Controller
public class MenuController extends BaseController{

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redis;

    @GetMapping("/menu_set")
    public String menu_set(Model model) throws JsonProcessingException {
        String jsonString = this.getMenuStr();
        //User user = this.getUserFromSession();
        //model.addAttribute("username",user.getUsername());
        model.addAttribute("jsonString","["+jsonString+"]");
        return "menu_set";
    }

    public @ResponseBody
    String menu_gets(String roleid) throws JsonProcessingException {
        SysPermission sp = this.getMenuObj();
        JSONObject menuRs = this.get_remote_data_list_nocache_noformat("query/role/select|*/where|id="+roleid,true,6000);
        JSONArray idsArr = new JSONArray();
        if(menuRs.getString("msg").equals("OK")) {
            JSONArray menuAl = (JSONArray) menuRs.get("data");
            JSONObject idsObj = (JSONObject) menuAl.get(0);
            idsArr = (JSONArray) JSON.parse(idsObj.get("ids").toString());
        }
        SysPermission newst = this.setSysPermission(sp);
        ArrayList<SysPermission> childst = new ArrayList<SysPermission>();
        for (SysPermission t : sp.getChildren()) {
            if(idsArr.contains(t.getId())){
                SysPermission tempst = new SysPermission();
                tempst = this.setSysPermission(t);
                ArrayList<SysPermission> childst1 = new ArrayList<SysPermission>();
                if(t.getChildren().size() > 0){
                    for (SysPermission t1 : t.getChildren()) {
                        if(idsArr.contains(t1.getId())){
                            childst1.add(this.setSysPermission(t1));
                        }
                    }
                }
                tempst.setChildren(childst1);
                childst.add(tempst);
            }
        }
        newst.setChildren(childst);
        return JSON.toJSONString(newst);
    }

    public @ResponseBody
    String front_menu_gets(String roleid) throws JsonProcessingException {
        SysPermission sp = this.getFontMenuObj();
        JSONObject menuRs = this.get_remote_data_list_nocache_noformat("query/role/select|*/where|id="+roleid,true,6000);
        JSONArray idsArr = new JSONArray();
        if(menuRs.getString("msg").equals("OK")) {
            JSONArray menuAl = (JSONArray) menuRs.get("data");
            JSONObject idsObj = (JSONObject) menuAl.get(0);
            idsArr = (JSONArray) JSON.parse(idsObj.get("ids").toString());
        }
        SysPermission newst = this.setSysPermission(sp);
        ArrayList<SysPermission> childst = new ArrayList<SysPermission>();
        for (SysPermission t : sp.getChildren()) {
            if(idsArr.contains(t.getId())){
                SysPermission tempst = new SysPermission();
                tempst = this.setSysPermission(t);
                ArrayList<SysPermission> childst1 = new ArrayList<SysPermission>();
                if(t.getChildren().size() > 0){
                    for (SysPermission t1 : t.getChildren()) {
                        if(idsArr.contains(t1.getId())){
                            childst1.add(this.setSysPermission(t1));
                        }
                    }
                }
                tempst.setChildren(childst1);
                childst.add(tempst);
            }
        }
        newst.setChildren(childst);
        return JSON.toJSONString(newst);
    }

    private SysPermission setSysPermission(SysPermission org){
        SysPermission dst = new SysPermission();
        dst.setId((Integer) org.getId());
        dst.setParentId((Integer) org.getParentId());
        dst.setName(String.valueOf(org.getName()));
        dst.setLevel((Integer) org.getLevel());
        dst.setUrl(String.valueOf(org.getUrl()));
        dst.setIcon(String.valueOf(org.getIcon()));
        dst.setChildren(new ArrayList<SysPermission>());
        return dst;
    }

    @GetMapping("/menu_list")
    @ResponseBody
    public Map<String,Object> list(){
        JSONObject rs = this.get_remote_data_list_noformat("get_tree/sys_permission/9999/1",true,120);
        System.out.println(rs);
        String submitstr = "";
        ArrayList fieldArr = new ArrayList();
        JSONArray objarr = new JSONArray();
        Map<String,Object> map = new HashMap<>();
        if(rs.getString("msg").equals("OK")){
            map.put("code",0);
            map.put("msg",null);
            map.put("data",rs.get("data"));
        }
        return map;
    }

    @GetMapping("/menu_gets_json")
    public @ResponseBody JSONResult menu_gets_json(Model model, HttpSession session) throws JsonProcessingException {
        String key = "menu_gets_json";
        if(this.redis.get(key) != null){
            System.out.println("read cache");
            return JSONResult.ok(0,(JSONObject) this.redis.get(key));
        }
        String content = this.menu_gets("2");
        JSONObject obj = (JSONObject) JSON.parse(content);
        this.redis.set(key,obj);
        return JSONResult.ok(0,obj);
    }

    @GetMapping("/front_menu_gets_json")
    public @ResponseBody JSONResult front_menu_gets_json(Model model, HttpSession session) throws JsonProcessingException {
        String key = "front_menu_gets_json";
        if(this.redis.get(key) != null){
            System.out.println("read cache");
            return JSONResult.ok(0,(JSONObject) this.redis.get(key));
        }
        String content = this.front_menu_gets("1");
        JSONObject obj = (JSONObject) JSON.parse(content);
        this.redis.set(key,obj);
        return JSONResult.ok(0,obj);
    }

    @GetMapping("/menu_gets_all")
    public @ResponseBody JSONResult menu_gets_all(Model model, HttpSession session) throws JsonProcessingException {
        String menuStr = "";
        String content = this.menu_gets("2");
        JSONObject obj = (JSONObject) JSON.parse(content);
        JSONArray al = (JSONArray) obj.get("children");
        for(int i=0;i<al.size();i++){
            JSONObject level1 = (JSONObject) al.get(i);
            JSONArray level2 = (JSONArray) level1.get("children");
            if(level2.size() >0){
                menuStr += "<lay-sub-menu>\n";
                menuStr += "<template #title>\n"+level1.get("name").toString()+"\n</template>\n";
                for(int m=0;m<level2.size();m++){
                    JSONObject level3 = (JSONObject) level2.get(m);
                    JSONArray level5 = (JSONArray) level3.get("children");
                    menuStr += "<lay-menu-item><a href='"+level3.get("url").toString()+"'>"+level3.get("name").toString()+"</a></lay-menu-item>\n";
                }
                menuStr += "</lay-sub-menu>\n";
            }else{
                menuStr += "<lay-menu-item><a href='"+level1.get("url").toString()+"'>"+level1.get("name").toString()+"</a></lay-menu-item>\n";
            }
        }
        return JSONResult.ok(0,menuStr);
    }

    @GetMapping("/ele_menu_gets_all")
    public @ResponseBody JSONResult ele_menu_gets_all(Model model, HttpSession session) throws JsonProcessingException {
        String menuStr = "<el-menu-item index='/manage_index'>首页</el-menu-item>";
        String content = this.menu_gets("2");
        JSONObject obj = (JSONObject) JSON.parse(content);
        JSONArray al = (JSONArray) obj.get("children");
        for(int i=0;i<al.size();i++){
            JSONObject level1 = (JSONObject) al.get(i);
            JSONArray level2 = (JSONArray) level1.get("children");
            if(level2.size() >0){
                menuStr += "<el-sub-menu index='"+ i +"'>";
                menuStr += "<template #title>"+level1.get("name").toString()+"</template>";
                for(int m=0;m<level2.size();m++){
                    JSONObject level3 = (JSONObject) level2.get(m);
                    JSONArray level5 = (JSONArray) level3.get("children");
                    menuStr += "<el-menu-item index='"+level3.get("url").toString()+"'>"+level3.get("name").toString()+"</el-menu-item>";
                }
                menuStr += "</el-sub-menu>";
            }else{
                menuStr += "<el-menu-item index='"+level1.get("url").toString()+"'>"+level1.get("name").toString()+"</el-menu-item>";
            }
        }
        return JSONResult.ok(0,menuStr);
    }

}
